import java.util.HashMap;
import java.util.Map;

/*
 * @lc app=leetcode.cn id=105 lang=java
 *
 * [105] 从前序与中序遍历序列构造二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    Map<Integer,Integer>map;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        map=new HashMap<>();
        for(int i=0;i<inorder.length;i++){
            map.put(inorder[i], i);
        }
        return dfs(preorder,0,preorder.length,inorder,0,inorder.length);
    }
    public TreeNode dfs(int[] preorder,int preBegin,int preEnd,int[] inorder,int inBegin,int inEnd){
        if(preBegin>=preEnd||inBegin>=inEnd){
            return null;
        }
        //找到根节点
        int rootIndex=map.get(preorder[preBegin]);
        TreeNode root=new TreeNode(inorder[rootIndex]);
        int lenOfLeft=rootIndex-inBegin;
        //构建左子树
        root.left=dfs(preorder,preBegin+1,preBegin+lenOfLeft+1,inorder,inBegin,rootIndex);
        //构建右子树
        root.right=dfs(preorder, preBegin+lenOfLeft+1, preEnd, inorder, rootIndex+1, inEnd);
        return root;

    }
}
// @lc code=end

